﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;
using System.Web.Script;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

namespace VersionManage.Common
{
    public static class JsonHelper
    {
        //List转成json
        public static string ListToJson<T>(IList<T> IL, string flag = "")
        {
            System.Text.StringBuilder Json = new StringBuilder();
            Json.Append("{\"flag\":\"" + flag + "\",\"json\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        object value = pis[j].GetValue(IL[i], null);
                        if (value != null && value.ToString() != "")
                        {
                            value = value.ToString().Replace('"', '“');
                        }

                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + value + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>
        /// 将json字符转换为Object
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="str">json字符串</param>
        /// <returns></returns>
        public static T ParseJSON<T>(this string jsonString)
        {
            string pattern = @"\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(pattern);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);

            return obj;
        }

        /// <summary>
        /// 将时间字符串转为Json时间
        /// </summary>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }


        /// <summary>
        /// List转化为Json
        /// </summary>
        /// 备注缺点:如datetime类型要在前台自己转化()
        public static string ListToJson<T>(T t,int totalCount)
        {
            JsonShowModel<T> jsonObj = new JsonShowModel<T>(totalCount, t);
            string jsonresult = new JavaScriptSerializer().Serialize(jsonObj);
            return jsonresult;
        }
        /// <summary>
        /// 当单一的Class实体转化为Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="IL"></param>
        /// <returns></returns>
        public static string SingleToJson<T>(T IL)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return serializer.Serialize(IL);
        }

        /// <summary>
        ///利用递归方法实现Json输入的深层递归
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="IL"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public static string ListToMSJson<T>(IList<T> IL, string flag = "")
        {
            System.Text.StringBuilder Json = new StringBuilder();
            Json.Append("{\"flag\":\"" + flag + "\",\"json\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    Type type = IL.FirstOrDefault().GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        Json.Append("\"" + pis[j].Name.ToString() + "\":" + ListToSingleMSJson(pis[j].GetValue(IL[i], null)));
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>
        /// 深层递归的辅助类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="IL"></param>
        /// <returns></returns>
        private static dynamic ListToSingleMSJson<T>(T ILSingle)
        {
            if ((ILSingle == null) || (!ILSingle.GetType().IsClass) || (ILSingle is string))
                return "\"" + ILSingle + "\"";

            StringBuilder Json = new StringBuilder();
            var IL = new List<T>() { ILSingle };
            Json.Append("[");
            for (int i = 0; i < IL.Count(); i++)
            {
                Type type = IL.FirstOrDefault().GetType();
                PropertyInfo[] pis = type.GetProperties();
                Json.Append("{");
                for (int j = 0; j < pis.Length; j++)
                {
                    Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                    if (j < pis.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < IL.Count() - 1)
                {
                    Json.Append(",");
                }
            }
            Json.Append("]");
            return Json.ToString();
        }

        /// <summary>
        /// 将object转换为json字符串
        /// </summary>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        public static string ToJson(Object source)
        {
            return ToJson(source, source.GetType());
        }
        /// <summary>
        /// 将object转换为json字符串
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="type">object数据类型</param>
        /// <returns></returns>
        public static string ToJson(Object source, Type type)
        {       
            DataContractJsonSerializer serilializer = new DataContractJsonSerializer(type);
            using (Stream stream = new MemoryStream())
            {
                serilializer.WriteObject(stream, source);
                stream.Flush();
                stream.Position = 0;
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// 状态，返回值
        /// </summary>
        public static string StatusToJson(int status, string content)
        {
            StringBuilder strbuiler = new StringBuilder();
            strbuiler.Append("{\"status\":\"");
            strbuiler.Append(status.ToString());
            strbuiler.Append("\",\"content\":\"");
            strbuiler.Append(content);
            strbuiler.Append("\"}");
            return strbuiler.ToString();
        }


    }

    public class JsonShowModel<T>
    {
        public JsonShowModel(int totalCount, T t)
        {
            flag = totalCount;
            json = t;
        }
        public int flag;

        public T json;
    }
}